package com.hbzhit.modules.wx.controller;

import com.hbzhit.common.utils.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Edward
 */
@AllArgsConstructor
@Controller
@RequestMapping("/wx/redirect")
public class WxRedirectController {
    private final WxMpService wxService;

    /**
     * 获取微信token和openid
     *
     * @param appid 公众号appID
     * @param code 用户授权的code
     * @return token数据
     */
    @SneakyThrows
    @RequestMapping("/getToken/{appid}")
    @ResponseBody
    public R<WxOAuth2AccessToken> getToken(@PathVariable String appid, @RequestParam String code) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
        return R.ok(accessToken);
    }

    /**
     * 用户授权后获取微信用户信息，返回数据
     * 需要 scope=snsapi_userinfo 的授权code
     *
     * @param appid 微信公众号appID
     * @param code 用户授权code
     * @return 数据
     */
    @RequestMapping("/getWxUser/{appid}")
    @SneakyThrows
    public R<WxOAuth2UserInfo> greetWxUser(@PathVariable String appid, @RequestParam String code, ModelMap map) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
        WxOAuth2UserInfo user = wxService.getOAuth2Service().getUserInfo(accessToken,"zh_CN");
        map.put("user", user);

        return R.ok(user);
    }

    /**
     * 创建调用jsapi时所需要的签名
     * @param appid 微信公众号appID
     * @param url 回调URL
     */
    @SneakyThrows
    @RequestMapping("/jsapiSign/{appid}")
    @ResponseBody
    public R<WxJsapiSignature> greetJsapiSign(@PathVariable String appid, @RequestParam String url) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        // url为html编码，符号需要转义，如：&amp; -> &
        String urlStr = StringEscapeUtils.unescapeHtml(url);
        WxJsapiSignature sign = wxService.createJsapiSignature(urlStr);
        return R.ok(sign);
    }
}
